package com.mmc.config;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * MyBatis Plus 配置类
 *
 * @author kunfe
 * @since 2024-01-01
 */
@Configuration
public class MybatisPlusConfig {

    /**
     * MyBatis Plus 拦截器配置
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        
        // 分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        
        // 乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        
        return interceptor;
    }

    /**
     * 字段自动填充处理器
     */
    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                LocalDateTime now = LocalDateTime.now();
                String operator = getCurrentUser();
                
                // 创建时间
                strictInsertFill(metaObject, "createTime", LocalDateTime.class, now);
                // 更新时间
                strictInsertFill(metaObject, "updateTime", LocalDateTime.class, now);
                // 创建人
                strictInsertFill(metaObject, "createBy", String.class, operator);
                // 更新人
                strictInsertFill(metaObject, "updateBy", String.class, operator);
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                LocalDateTime now = LocalDateTime.now();
                String operator = getCurrentUser();
                
                // 更新时间
                strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, now);
                // 更新人
                strictUpdateFill(metaObject, "updateBy", String.class, operator);
            }

            /**
             * 获取当前操作用户
             */
            private String getCurrentUser() {
                try {
                    return StpUtil.getLoginIdAsString();
                } catch (Exception e) {
                    return "system";
                }
            }
        };
    }
} 